import argparse
import logging
import os
import sys

from ocup.base import Ocup
from ocup.constants import OCUP_LOCK
from ocup.logger import setup_logger
from ocup.version import VERSION

if not os.geteuid() == 0:
    print("no root privileges,please use the root to perform the upgrade", file=sys.stderr)
    exit(1)
setup_logger()
logger = logging.getLogger("ocup")


def main():
    version = "{0}-{1}".format(os.path.basename(sys.argv[0]), VERSION)
    parser = argparse.ArgumentParser(description='OpenCloud OS upgrade tool.')
    parser.add_argument('-u', '--upgrade', action='store_true', help='upgrade OpenCloud OS')

    parser.add_argument('-v', '--version', action='version', version=version,
                        help='print version information and exit')

    parser.add_argument('-d', '--daemon', action='store_true', help='run ocup in the background')

    parser.add_argument('-s', '--status', action='store_true', help='get ocup status')

    args = parser.parse_args()
    if args.daemon:
        if os.path.exists(OCUP_LOCK):
            logger.error("ocup is already running")
            exit(1)
        logger.info("Upgrading os in backend")
        Ocup().start()
    elif args.upgrade:
        if os.path.exists(OCUP_LOCK):
            logger.error("ocup is already running")
            exit(1)
        logger.info("Upgrading os in front")
        Ocup().run()
    elif args.status:
        logger.debug("get ocup status")
        Ocup().status()
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
